package selef.xiafan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import selef.xiafan.dao.ImageDao;
import selef.xiafan.entity.Image;
import selef.xiafan.util.UUIDUtils;
import selef.xiafan.util.result.FileResult;
import selef.xiafan.util.result.Result;
import selef.xiafan.util.result.ResultFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author xiafan
 * @version 1.0
 * @date 2021/8/13 17:38
 */
@RestController
@RequestMapping("/api")
public class ImageController {

    @Autowired
    ImageDao imageDao;

    @PostMapping("/image/upload")
    /**
     * 上传图片接口
     * */
    public FileResult upload(@RequestParam("picture") MultipartFile picture) {

        //获取文件在服务器的储存位置
        String path = "D://WorkFile//IdeaProject//Repair//4S-system//src//main//resources//static//uploadImage//";
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = picture.getOriginalFilename();

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        String fileName = UUIDUtils.getUUID32() + name + "." + type;

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);

        //将文件保存到服务器指定位置，1.保存时名字重复
        try {
            picture.transferTo(targetFile);
            Image image = new Image();
            image.setImageId(UUID.randomUUID().toString().substring(0,4));
            image.setSrc(path+fileName);
            image.setName(name);
            imageDao.save(image);
            //将文件在服务器的存储路径返回
            return new FileResult(true,fileName,path+"/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new FileResult(false, "上传失败","");
        }
    }



    /**
     * 显示图片
     * getFeedBackPicture.do?picName=
     * @return
     */

    @RequestMapping("/viewPhoto")
    public void getFeedBackPicture(@RequestBody Image image,HttpServletResponse response) throws Exception{
        FileInputStream inputStream = new FileInputStream(image.getSrc());
        int i = inputStream.available();
        //byte数组用于存放图片字节数据
        byte[] buff = new byte[i];
        inputStream.read(buff);
        //记得关闭输入流
        inputStream.close();
        //设置发送到客户端的响应内容类型
        response.setContentType("image/*");
        OutputStream out = response.getOutputStream();
        out.write(buff);
        //关闭响应输出流
        out.close();
    }

    @PostMapping("/image/delete")
    @Transactional
    public Result delete(@RequestBody Image image){
        String src = "D://WorkFile//IdeaProject//Repair//4S-system//src//main//resources//static//uploadImage//"+image.getName();
        Image bySrc = imageDao.findBySrc(src);
        File file = new File(src);
        if(file.exists()){
            file.delete();
        }
        if(bySrc!=null){
            imageDao.delete(bySrc);
            return ResultFactory.buildSuccessResult("删除成功");
        }
       return ResultFactory.buildFailResult("");
    }


}


